# -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 16:48:00 2015

@author: Luoge
"""
####################################
####将CSV文件转换为libSVM格式文件####
####################################

import csv

def ConvertCSV2LibSVM(csvFileName, libsvmFileName):
    csvfile = file(csvFileName, 'rb')
    fileObj = open(libsvmFileName, 'w')
    
    reader = csv.reader(csvfile)
    firstLine = reader.next()
    featrueCount = len(firstLine)
    kks = [x for x in range(featrueCount)]

    csvfile.seek(0)

    for line in reader:       
        tempdict = dict(zip(kks,line))
        
        # write label column
        labelStr = "{0} ".format(line[0])
        fileObj.write(labelStr)
#        print("labelStr:"+labelStr)
        
        # delete the label column from dict
        tempdict.pop(0,'not found')
        
        # write the rest of column to file 
        tstr = ""
        for k, v in tempdict.items():
            tstr =tstr + "{0}:{1} ".format(k, v)
        tstr = tstr + "\n"
#        print("tstr:" + tstr)
        
        fileObj.write(tstr)

    csvfile.close()
    fileObj.close()
    print("write finished!")

if __name__ == "__main__":
    csvFileName = r"h:\RSIA_SVM\result\Label_Features.csv"
    libsvmFileName=r"h:\RSIA_SVM\result\Label_Features.txt"
    ConvertCSV2LibSVM(csvFileName, libsvmFileName)
    
#    kk = ['one', 'two', 'three']
#    vv = [1, 2, 3]
#    c = dict(zip(kk,vv))
#    print(c)
#    tt=""
#    for k, v in c.items():
#        tt = tt + "{0}:{1} ".format(k,v)
#    print(tt)
